import polyfill from 'assets/plugins/polyfill'
import WxValidate from 'helpers/WxValidate'
import HttpResource from 'helpers/HttpResource'
import HttpService from 'helpers/HttpService'
import WxService from 'helpers/WxService'
import Tools from 'helpers/Tools'
import Config from 'etc/config'


App({
  onLaunch: function () {

  },
  myUlife: {
    ulifeUrl: "https://stgl.qcyjpt.com/stgl/"
    //ulifeUrl: "https://1da5bd0a.4kb.cn/stgl/"
  }, 
  WxValidate: (rules, messages) => new WxValidate(rules, messages),
  HttpResource: (url, paramDefaults, actions, options) => new HttpResource(url, paramDefaults, actions, options).init(),
  HttpService: new HttpService,
  WxService: new WxService,
  Tools: new Tools,
  Config: Config,
  code: '',
  
  //自动登录代码
  autologin: function (e) {
    wx.clearStorageSync();//去掉缓存
    wx.clearStorage();//去掉缓存
    var that = this;
    wx.showLoading({
      title: '加载中......',
    })
    if (wx.getSetting) {
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userInfo']) {
            wx.authorize({
              scope: 'scope.userInfo',
              success() {
                // 登录
                that.wxlogin();
              }
            })
          } else {
            // 登录
            that.wxlogin();
          }
        }
      })
    } else {
      //不兼容处理
      // 登录
      that.wxlogin();
    }
  },

  // 登录start
  wxlogin: function () {
    var that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        that.code = res.code;
        that.getwxuserinfo();
      }
    })
  },
  
  // 发送 res.code 到后台换取 openId, sessionKey, unionId
  getwxuserinfo: function () {
    var that=this;
    wx.request({
      url: that.myUlife.ulifeUrl + '/wechart/getwxuserinfo.html',//请求地址
      data: {
        code: that.code
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var openid = res.data.openid;
        wx.setStorageSync('openid', openid);//加入缓存
        wx.getUserInfo({
          success: res => {
            wx.hideLoading(res.userInfo);
            //加入缓存
            wx.setStorageSync('city', res.userInfo.city);
            wx.setStorageSync('province', res.userInfo.province);
            wx.setStorageSync('gender', res.userInfo.gender);
            wx.setStorageSync('nickName', res.userInfo.nickName);
            wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl);         
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            if (that.userInfoReadyCallback) {
              that.userInfoReadyCallback(res)
            }
          }
        })
      }
    })
  },

})